<template>
    <div class="cart-box">
        <!-- <h2>购物车</h2> -->
        <div class="header">
            <van-nav-bar title="购物车"
            :right-text="isEdit ? '完成' : '管理'"
            @click-right="managementEvt"
             left-text="<" @click="router.go(-1)"/>
        </div>
        <div class="content">
            <div class="goods">
                <van-checkbox checked-color="#006d75" rou> 国内到货 &nbsp;<input type="text" placeholder="请输入地址&nbsp;省/市/区/XX/门牌号" style="width: 200px; ">  </van-checkbox>
                <!-- <input type="checkbox"> 国内到货() -->
            </div>
            <div class="discount">
                <div class="dis-goods">
                    <div class="title"><span class="spec">精选特价</span><span>特价现货 · 抢完即止</span></div>
                    <div class="big-box">
                        <div class="choice" v-for="it in recommand" :key="it.id">
                            <div class="pic">
                                <img :src="baseURL + it.path" alt="">
                            </div>
                            <p>{{ it.title }}</p>
                            <span>¥ {{ it.price }}</span>
                        </div>

                    </div>
                </div>
            </div>
            <div class="buy">
                <div class="item-cls" v-for="it in list" :key="it.id">
                    <div class="check">
                        <van-checkbox checked-color="@b5" v-model="it.checked"></van-checkbox>
                    </div>
                    <img :src="baseURL + it.bgUrl" alt="">
                    <div class="info">
                        <div class="title">{{ it.name }}</div>
                        <div class="footer">
                            <span class="p">
                                ¥ <span>{{ it.price }}</span>
                            </span>
                            <div class="btns">
                                <van-button size="mini" icon="plus" @click="AddEvt(it)" round />
                                {{ it.count }}
                                <van-button size="mini" icon="minus" @click="MinusEvt(it)" round />
                            </div>
                        </div>
                    </div>
                </div>
             <div class="bottom">

             </div>
            </div>
        </div>
        <!-- <BlankContent/> -->
        <van-submit-bar :price="amount * 100" 
        :button-text="(isEdit ? '删除' : '提交') + `(${total})`"
            @submit="submitEvt">
            <van-checkbox checked-color="@b5" v-model="checkAll">全选</van-checkbox>
        </van-submit-bar>
    </div>
</template>
<script lang="ts" setup>
/** 全局变量 */
const baseURL = window.baseURL;

import { Ref, ref, watch ,computed,ComputedRef,} from 'vue'
import { showConfirmDialog, showToast, } from "vant";
// import { useCommonStore } from '../../store';
import { homeRecommendApi, cartListApi, cartModifyApi,cartDeleteApi, orderAddApi} from '../../apis/homeApi'
import { useRouter } from 'vue-router';
// import list from 'vant/lib/list';
const router=useRouter()
const checkAll: Ref<boolean> = ref(false)
const recommand: Ref<Array<any>> = ref([])
const list: Ref<Array<any>> = ref([])
const page: Ref<number> = ref(1)
getList();
async function getList() {
    //   let _res = await homeRecommendApi(page.value,200 )
    let _res = await homeRecommendApi(page.value, 200)
    if (_res.code === 200) {
        recommand.value = _res.data.rows;
    }

}
// 请求购物车列表
cartList();
async function cartList() {
    console.log();
    const userid: any = localStorage.getItem('userid')
    let _res = await cartListApi(userid);
    if (_res.code == 200) {
        list.value = _res.data.map((item: any) => {
            item.checked = false
            return item
        })
    }
    console.log(list.value);

}
//全选
watch(
    () => list.value,
    function () {
        checkAll.value = list.value.every((oo: any) => oo.checked);
    },
    {
        deep: true
    }
)
watch(
    () => checkAll.value,
    function () {
        list.value.forEach((it: any) => {
            it.checked = checkAll.value
                
        })
    }
)
/** 累计金额 */
const amount: ComputedRef<number> = computed(() => {
    return list.value.reduce((r: number, it: any) => {
        if (it.checked) r += it.price * it.count;
        return r
    }, 0)
})
/** 累计数量 */
const total: ComputedRef<number> = computed(() => {
    return list.value.reduce((r: number, it: any) => {
        if (it.checked) r += it.count;
        return r
    }, 0)
})
/** 管理按钮点击事件 */
const isEdit: Ref<boolean> = ref(false);
function managementEvt() {
    isEdit.value = !isEdit.value;
}
/** 提交按钮 -- (是编辑状态)删除和(不是)提交订单功能 */
async function submitEvt() {
    let _list = JSON.parse(JSON.stringify(list.value.filter((oo: any) => oo.checked))).map((it: any) => {
        delete it.checked;
        it.userId = it.userid;
        return it;
    })
    const userid: any = localStorage.getItem('userid')
    if (!isEdit.value) {
        let _res = await orderAddApi({
            "userId": userid,
            "list": _list
        })
        if (_res.code === 200) {
            showToast('提交订单成功')
            getList();
        }
    } else {
        let ids = _list.map((it: any) => it.id);
        let _ret = await cartDeleteApi({userId: userid, ids});
        if (_ret.code === 200) {
            list.value = list.value.filter((oo: any) => !ids.includes(oo.id));
        }
    }
} 
    //添加和修改

    function AddEvt(it: any) {
        const userid: any = localStorage.getItem('userid')
        it.count += 1
        cartModifyApi({
            userId: userid + '',
            id: it.id + '',
            count: it.count
        }).then(da => {
            console.log(da);

        })
        // cartList()

    }
function MinusEvt(it: any) {
        if (it.count <= 1) {
            let a = showConfirmDialog({
                title: '删除确认',
                message: '确定不考虑一下了，残忍删除！'
            }).then(a => {
                // console.log(a);
                if (a) {
                    const userid: any = localStorage.getItem('userid')
                    it.count -= 1
                    cartModifyApi({
                        userId: userid + '',
                        id: it.id + '',
                        count: it.count
                    }).then(da => {
                        console.log(da);
                        cartList()
                    })

                }
            })

            console.log(a);

        } else {
            const userid: any = localStorage.getItem('userid')
            it.count -= 1
            cartModifyApi({
                userId: userid + '',
                id: it.id + '',
                count: it.count
            }).then(da => {
                console.log(da);
                cartList()
            })
        }
        // return


        //         .then(async (a) => {
        //             console.log(a);

        //             let obj ={userId: userid, ids: [ it.id + '' ]}
        //             console.log(obj);
        //             let _ret = await cartDeleteApi(obj)
        //             console.log(_ret);

        //             if (_ret.code === 200) {
        //                 console.log(1111);

        //                 list.value.splice(list.value.findIndex((oo: any) => oo.id === it.id), 1);
        //             }
        //         }).catch(() => {})
        //     } else {
        //         next = true;
        //         it.count = it.count * 1 - 1;
    }
// }
// if (!next) return;
// let _res = await cartModifyApi({
//     userId: userid+'',
//         id: it.id+'',
//     count: it.count
// });
// if (_res.code === 200) {
//     it.count = obj.count
// }
//}}}}}]}}}}}}



</script>
<style lang="less" scoped>
@import "../../style/common.less";

.cart-box {
    overflow-x: hidden;
    display: block;
    position: relative;
    height: 100%-50px;

    .van-submit-bar {
        // position: absolute;
        bottom: 50px;
    }

    ::v-deep .van-nav-bar__content {
        height: 60px;
    }

    ::v-deep .van-submit-bar__price {
        color: @b5;
    }

    ::v-deep .van-submit-bar__button--danger {
        background: @b5;
    }

    >.content {
        background-color: #f1f2f4;

        >.goods {
            font-size: 14px;
            padding: 10px 10px;
            background-color: white;
            // border: 1px solid red;
        }

        >.discount {
            height: 220px;
            background-color: white;
            height: 100%;
            margin-bottom: 10px;

            >.dis-goods {
                height: 200px;
                width: 92%;
                background-color: #eef5fe;
                margin: 0 auto;
                border-radius: 10px;

                >.title {
                    height: 30px;
                    font-size: 12px;
                    color: @b3;
                    line-height: 30px;

                    >.spec {
                        display: inline-block;
                        height: 30px;
                        width: 80px;
                        background-color: @b4;
                        font-size: 14px;
                        color: white;
                        font-weight: bold;
                        text-align: center;
                        border-top-left-radius: 14px;
                        border-bottom-right-radius: 20px;
                        margin-right: 16px;
                    }
                }

                >.big-box {
                    width: 100%;
                    display: flex;
                    overflow-x: scroll;
                    flex-wrap: nowrap;

                    &::-webkit-scrollbar {
                        display: none;
                    }

                    >.choice {
                        flex: 0 0 25%;
                        width: 24%;
                        height: 155px;
                        margin-top: 10px;
                        background-color: white;
                        margin: 10px 6px;
                        border-radius: 6px;
                        overflow: hidden;

                        >.pic {
                            width: 110px;
                            height: 110px;

                            >img {
                                width: 100%;
                                height: 100%;
                            }

                        }

                        >p {
                            height: 25px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: normal;
                            -webkit-box-orient: vertical;
                            -webkit-line-clamp: 2;
                            font-size: .7rem;
                            color: @b5;
                            line-height: 20px;
                            padding: 4px 10px;
                            display: -webkit-box;
                            color: @b3;
                        }

                        >span {
                            color: @b7;
                            font-size: 12px;
                        }
                    }
                }
            }
        }

        .item-cls {
            display: flex;
            position: relative;
            padding: 8px;
            background: @g01;
            box-shadow: 0 0 12px rgba(0, 0, 0, .05);
            border-radius: 6px;
            margin-bottom: 12px;
            // align-items: center;

            >.check {
                flex: 0 0 20px;
                width: 0;
                text-align: center;
                line-height: 110px;

                >.van-checkbox {
                    display: inline-block;
                }
            }

            >img {
                // flex: 0 0 110px;
                width: 70px;
                height: 70px;
            }

            >.info {
                flex: 1;
                width: 0;
                position: relative;
                padding-left: 6px;

                >.title {
                    font-size: .7rem;
                    color: @g10;
                    font-weight: bold;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: normal;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    line-height: 20px;
                    display: -webkit-box;
                }

                >.footer {
                    position: absolute;
                    bottom: 10px;
                    left: 6px;
                    width: calc(100% - 6px);
                    overflow: hidden;
                    line-height: 32px;

                    >.p {
                        display: block;
                        float: left;
                        font-size: .6rem;
                        color: @b7;
                        width: 90px;

                        >span {
                            text-indent: 4px;
                            font-size: 1rem;
                        }
                    }

                    >.btns {
                        float: right;
                        font-size: .9rem;

                        .van-button {
                            vertical-align: text-top;
                            color: @g10;
                        }
                    }
                }
            }
        }
        .bottom{
            height: 100px;
        }

    }
}
</style>